package com.lt.flashcard.view;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.zkoss.bind.annotation.BindingParam;
import org.zkoss.bind.annotation.Command;
import org.zkoss.bind.annotation.Init;
import org.zkoss.bind.annotation.NotifyChange;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.util.Clients;

import com.lt.flashcard.Utility;
import com.lt.flashcard.bind.ConstraintValidator;
import com.lt.flashcard.model.entity.Activity;
import com.lt.flashcard.model.entity.User;
import com.lt.flashcard.model.service.AAService;
import com.lt.flashcard.model.service.EmailService;
import com.lt.flashcard.model.service.Repository;
import com.lt.flashcard.model.service.UserService;

public class ProfileFriendlistVm {
	
	private User user;//Current displayed user
	
	private String search;//the search string
	
	private int searchIndex = 0;//the search option
	
	private List<Activity> activities; //store activities
	
	private List<User> friends;
	
	private String screen = "activity";
	
	private String email = "";
	
	private String message = "";
	
	private ConstraintValidator constraintvalidator;
	
	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}
	
	@Init
	public void init() {
		String Id = Executions.getCurrent().getParameter("id");
		UserService usrv = Repository.getInstance().getUserService();
		AAService asrv = Repository.getInstance().getAAService();
		User cuser = asrv.getCurrentUser();
		if(Id == null) {
			if(!asrv.isLogin()) {
				Utility.loginOrAccessDenied(false);
				return;
			}
			else {
				user = cuser;
			}
		}
		else {
			user = usrv.findByID(new Long(Id));
			if(user == null) {
				Utility.displayAccessDenied(false);
				return;
			}
		}
		
		if(user != null && asrv.isAdmin(user)){
			if(cuser == null || (cuser != null && !user.getId().equals(cuser.getId()))){
				Utility.displayAccessDenied(false);
				return;
			}
		}
		
		owner = user != null && cuser != null && user.getId().equals(cuser.getId());
		
		activities = usrv.getAllActivitiesOfFriends(getUser().getId());
		buildFriendList();
		constraintvalidator = new ConstraintValidator();
	}
	
	/**
	 * Build the friend list to display on the left, base on the search condition
	 */
	private void buildFriendList() {
		UserService usrv = Repository.getInstance().getUserService();
        if (StringUtils.isNotBlank(search)) {
			friends = new ArrayList<User>(usrv.searchAllFriends(getUser(), search, true));
			friends.addAll(usrv.searchAllUsers(search, true));
		}
		else
			friends = usrv.getFriendList(getUser());
	}
	
	/**
	 * Return list of friends of current user
	 * @return
	 */
	public List<User> getFriends() {
		return friends;
	}
	
	/**
	 * Get friends of friends as suggested friends
	 * @return
	 */
	public List<User> getFriendsOfFriends() {
		UserService usrv = Repository.getInstance().getUserService();
		return usrv.getFriendsOfFriends(getUser(), 4);
	}
	
	public int getNumOfFriends() {
		return friends == null ? 0 : friends.size();
	}

	public String getSearch() {
		return search;
	}

	public void setSearch(String search) {
		this.search = search;
	}
	
	/**
	 * Do the search
	 */
	@NotifyChange("friends")
	@Command
	public void dosearch() {
		buildFriendList();
	}

	public int getSearchIndex() {
		return searchIndex;
	}
	
	@NotifyChange("screen")
	@Command
	public void changescreen(@BindingParam("screen") String screen) {
		this.screen = screen;
	}
	
	@Command
	public void invitebyemail() {
		//validate email
		UserService usrv = Repository.getInstance().getUserService();
		List<String> validEmails = new ArrayList<String>();
		String[] emails = email.split(",");
		for(String e : emails) {
			e = e.trim();
			if(e.matches(".+@.+.[a-z]+") && !usrv.isEmailExist(e))
				validEmails.add(e);
		}
		if(validEmails.size() == 0) {
            Clients.evalJavaScript("showNotice('', 'Email không hợp lệ hoặc bị trùng')");
			return;
		}
		User user = Utility.getUser();
		try {
			EmailService esrv = Repository.getInstance().getEmailService();
			esrv.sendEmailInviteFriend(user.getEmail(), user.getName(), validEmails, message);
            Clients.evalJavaScript("showNotice('', 'Hoàn tất')");
		} catch (Exception e) {
			e.printStackTrace();
            Clients.evalJavaScript("showNotice('', 'Có lỗi')");
		}
	}
	
	private boolean owner = false;
	public boolean isOwner() {
		return owner;
	}

	public void setSearchIndex(int searchIndex) {
		this.searchIndex = searchIndex;
	}

	public List<Activity> getActivities() {
		return activities;
	}

	public void setActivities(List<Activity> activities) {
		this.activities = activities;
	}

	public String getScreen() {
		return screen;
	}

	public void setScreen(String screen) {
		this.screen = screen;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public ConstraintValidator getConstraintvalidator() {
		return constraintvalidator;
	}

	public void setConstraintvalidator(ConstraintValidator constraintvalidator) {
		this.constraintvalidator = constraintvalidator;
	}
}